package com.qidian.permission.service.impl;

import com.qidian.permission.entity.User;
import com.qidian.permission.mapper.UserMapper;
import com.qidian.permission.service.UserService;
import com.qidian.permission.util.entity.Pager;
import com.qidian.permission.util.entity.PerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @Time 2023/10/18 10:19
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public PerResult queryById(Long userId) {
        User user = null;
        if ((user = userMapper.selectById(userId)) != null){
            return PerResult.ok(user);
        }
        return PerResult.empty();
    }

    @Override
    public PerResult save(User user) {
        // 校验用户名是否重复
        if(user.getUsername() != null && userMapper.selectByUsername(user.getUsername()) != null){
            return PerResult.duplicate("用户名重复");
        }
        // updateIsOk会根据传入的参数判断返回的结果
        return PerResult.updateIsOk(userMapper.save(user));
    }

    @Override
    public PerResult queryByPage(User user, int page, int limit) {
        Pager<User> pager = new Pager<>();
        pager.setCurr(page);
        pager.setLimit(limit);
        pager.setTotal(userMapper.selectCount(user));
        pager.setData(userMapper.selectByPage(user,(page - 1) * limit,limit));
        pager.setMaxPageNum((int)(Math.ceil(pager.getTotal() * 1.0 / limit)));
        return PerResult.ok(pager);
    }

    @Override
    public PerResult update(User user) {
        // 校验是否重复
        User userTemp = userMapper.selectByUsername(user.getUsername());
        if(userTemp != null && !userTemp.getUserId().equals(user.getUserId())){
            return PerResult.duplicate("用户名重复");
        }
        return PerResult.updateIsOk(userMapper.update(user));
    }

    @Override
    public PerResult deleteByUserId(Long userId){
        return PerResult.updateIsOk(userMapper.deleteByUserId(userId));
    };

    @Override
    public PerResult deletesByUserId(Long []userId){
        int count = userMapper.deletesByUserId(userId);
        return PerResult.ok(count + "");
    };
}
